package com.example.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author FKJGFK
 * @version 1.0.0
 * @ClassName filter.java
 * @Description TODO
 * @createTime 2021/11/01 10:19:25
 */
@Component
public class ZuulAuthFlter extends ZuulFilter {

	/**
	 * 在请求前pre或者后post执行
	 *
	 * @return
	 */
	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	/**
	 * 过滤器内执行的操作 return 任何Object的值都表示继续执行
	 * setSendZuulResponse(false)表示不再继续执行
	 *
	 * @return
	 * @throws ZuulException
	 */
	@Override
	public Object run() throws ZuulException {
		System.out.println("经过后台过滤器了！");

		//request对象
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();

		//经过网关寻址、请求 是两次，包含OPTIONS的请求不拦截
		if (request.getMethod().equals("OPTIONS")) {
			return null;
		}

		//public放行
		if (request.getRequestURI().indexOf("login") > 0) {
			return null;
		}

		//得到头信息
		String header = request.getHeader("Authorization");
		if (StringUtils.isNotEmpty(header)) {
			if (header.startsWith("Bearer ")) {
				String token = header.substring(7);
				//todo 校验token
				if (true) {
					return null;
				}
			}
		}

		//终止运行
		requestContext.setSendZuulResponse(false);
		requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
		requestContext.setResponseBody("权限不足");
		requestContext.getResponse().setContentType("text/html;charset=utf-8");
		return null;
	}

}
